package com.leaf.u.basehttp.http.response;

import com.leaf.u.basehttp.download.Headers;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public final class LeafResponse {
    private final int code;
    private final Headers headers;
    private final long contentLength;
    private final InputStream inputStream;
    private String original;
    private String parseStr;

    private LeafResponse(Builder builder) {
        this.code = builder.code;
        this.headers = builder.headers;
        this.contentLength = builder.contentLength;
        this.inputStream = builder.inputStream;
    }


    public int code() {
        return this.code;
    }


    public String treadtedString() {
        return this.parseStr;
    }

    public void setTreated(String treated) {
        this.parseStr = treated;
    }


    public Headers headers() {
        return this.headers;
    }

    public long contentLength() {
        return this.contentLength;
    }

    public InputStream inputStream() {
        return this.inputStream;
    }

    public String header(String name) {
        return header(name, null);
    }

    public String header(String name, String defaultValue) {
        String result = headers.get(name);
        return result != null ? result : defaultValue;
    }

    public String original() {
        if (inputStream == null || original != null) {
            return this.original;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        try {
            while ((i = inputStream.read()) != -1) {
                baos.write(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return original = baos.toString();
    }

    public static class Builder {
        private int code;
        private Headers headers;
        private long contentLength;
        private InputStream inputStream;

        public LeafResponse build() {
            return new LeafResponse(this);
        }

        public Builder setCode(int code) {
            this.code = code;
            return this;
        }

        public Builder setHeaders(Headers headers) {
            this.headers = headers;
            return this;
        }

        public Builder setContentLength(long contentLength) {
            this.contentLength = contentLength;
            return this;
        }

        public Builder setInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
            return this;
        }
    }

}
